package cn.jsxz.common.utils.Queue;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class BlockingQueueTest {
    //创建队列
    LinkedBlockingQueue<Object> basket = new LinkedBlockingQueue<Object>();

    // 生产苹果，放入篮子
    public void produce(String name) throws InterruptedException {
        // put方法放入一个苹果，若basket满了，等到basket有位置
        basket.put(name + "=====");
    }

    // 消费苹果，从篮子中取走
    public String consume() throws InterruptedException {
        // get方法取出一个苹果，若basket为空，等到basket有苹果为止
        String apple = basket.take().toString();
        return apple;
    }


    public int getAppleNumber() {
        return basket.size();
    }

    //　测试方法
    public void testBasket() {
        // 建立一个装苹果的篮子
        // 定义苹果生产者
        class Producer implements Runnable {
            private String name;

            public void setName(String name) {
                this.name = name;
            }

            public void run() {
                try {
                    while (true) {
                        // 生产苹果
                        System.out.println("生产者准备生产苹果：");
                        produce(name);
                        System.out.println(name);
                        System.out.println("生产者生产苹果完毕：");
                        System.out.println("生产完后有苹果：" + getAppleNumber() + "个");
                        // 休眠300ms
                        Thread.sleep(300);
                    }
                } catch (InterruptedException ex) {
                }
            }
        }

        //消费者
        class Consumer implements Runnable {
            public void run() {
                try {
                    while (true) {
                        // 消费苹果
                        System.out.println("消费者准备消费苹果");
                        String consume = consume();
                        System.out.println(consume);
                        System.out.println("消费者消费苹果完毕：");
                        System.out.println("消费完后有苹果：" + getAppleNumber() + "个");
                        // 休眠1000ms
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException ex) {
                }
            }
        }

        ExecutorService service = Executors.newCachedThreadPool();//创建线程池
        Producer producer = new Producer();//生产者对象
        Consumer consumer = new Consumer();
        producer.setName("zyyy");
        service.submit(producer);//启动放线程
        service.submit(consumer);//启动取线程
        // 程序运行10s后，所有任务停止
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        }

//        service.shutdown();//跑完再杀死
        service.shutdownNow();//完全杀死
    }

    public static void main(String[] args) {
        BlockingQueueTest test = new BlockingQueueTest();
        test.testBasket();
    }
}
